<template>
  <view class="container">
	<!-- <img class="imgstyle" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" src="/static/imgs/3.png" alt="" srcset="" /> -->
   <canvas
      canvas-id="smoothTrackCanvas"
      class="canvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
    ></canvas>
	<view class="showkm">
		<text style="font-size: 60upx;">{{datas.title}}:</text> <text>{{this.kmnum}}km</text>
	</view>
	<view @tap="RunOver" :class="['stopclass',datas.bgcolor]">
		<text>结束</text>
	</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 300, // 画布宽度
      canvasHeight: 480, // 画布高度
	  kmnum:0,
	  num:0,
	  isover:false,
      points: [
        { x: this.randomNum(30,50), y: this.randomNum(430,450) }, // 起点（底部）
        { x: this.randomNum(30,50), y: this.randomNum(390,420) }, // 折线点 1
        { x: this.randomNum(90,150), y: this.randomNum(350,400) }, // 中间点 1（避免直角）
        { x: this.randomNum(130,180), y: this.randomNum(380,420) }, // 折线点 2
        { x: this.randomNum(130,180), y: this.randomNum(330,380) }, // 折线点 3
        { x: this.randomNum(190,230), y: this.randomNum(300,350) }, // 中间点 2（避免直角）
        { x: this.randomNum(240,280), y: this.randomNum(330,380) }, // 折线点 4
        { x: this.randomNum(240,280), y: this.randomNum(280,320) }, // 折线点 5
        { x: this.randomNum(190,220), y: this.randomNum(260,300) }, // 中间点 3（避免直角）
        { x: this.randomNum(130,180), y: this.randomNum(280,320) }, // 折线点 6
        { x: this.randomNum(130,180), y: this.randomNum(230,280)}, // 折线点 7
        { x: this.randomNum(90,150), y: this.randomNum(200,260) }, // 中间点 4（避免直角）
        { x: this.randomNum(30,80), y: this.randomNum(90,380) }, // 折线点 8
        { x: this.randomNum(190,220), y: 20 }, // 终点（顶部）
      ],
      animationProgress: 0, // 动画进度（0 到 1）
      flashProgress: 0, // 闪烁效果进度
	  datas:{} //运动数据
    };
  },
  
  onLoad(option){
	  this.datas = JSON.parse(option.datas); //传输的内容数组
	  console.log(this.datas);
  },
  onReady() {
    this.drawSmoothTrack();
    this.startAnimation();
  },
  methods: {
	  RunOver(){
		  let type = "one"
		  let id = 1;
		  if(this.datas.title==="跑步"){
		  	type = "one"
			id = 1;
		  }else if(this.datas.title==="健步走"){
			  type = "two"
			  id = 2;
		  }else if(this.datas.title==="骑行"){
				type = "three"
				id = 3;
		  }else {
			  type = "four"
			  id = 4;
		  }
		  
		  if(uni.getStorageSync("runData")){
			  let arr = JSON.parse(uni.getStorageSync("runData"));
			  let obj = {
			  	id,
			  	type,
			  	name:this.datas.title,
			  	num:this.kmnum
			  }
			  let index =  arr.findIndex(item=>item.id==id);
			  if(index=="-1"){
			  	arr.push(obj)
			  }else{
			  	arr[index] = obj;
			  }
			  uni.setStorageSync("runData",JSON.stringify(arr));
			  
			  
		  }else{
			  
			  let obj = {
			  	id,
			  	type,
			  	name:this.datas.title,
			  	num:this.kmnum
			  }
			  uni.setStorageSync("runData",JSON.stringify([obj]));
			  
		  }
		  
		
		
		this.isover = true;
		uni.navigateTo({
			url:"../../../pages/index"
		})
		
	  },
	  randomNum(min,max){
	  	    return Math.random() * (max - min) + min;
	  },
    // 绘制平滑轨迹
    drawSmoothTrack() {
      const ctx = uni.createCanvasContext('smoothTrackCanvas', this);
      ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

      // 绘制背景
      // ctx.fillStyle = '#f0f0f0';
      // ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

      // 绘制平滑轨迹
      ctx.beginPath();
      ctx.moveTo(this.points[0].x, this.points[0].y); // 起点

      // 使用折线和贝塞尔曲线连接各个点
      for (let i = 1; i < this.points.length; i++) {
        if (i % 3 === 0) {
          // 每 3 个点使用贝塞尔曲线平滑连接
          const controlPoint = this.points[i - 1];
          const endPoint = this.points[i];
          ctx.quadraticCurveTo(
            controlPoint.x,
            controlPoint.y,
            endPoint.x,
            endPoint.y
          );
        } else {
          // 折线部分
          ctx.lineTo(this.points[i].x, this.points[i].y);
        }
      }

      ctx.strokeStyle = '#3c5054';
      ctx.lineWidth = 5;
      ctx.stroke();

      // 绘制起点和终点
      this.drawPoint(ctx, this.points[0], '#18cfbb'); // 起点
      this.drawPoint(ctx, this.points[this.points.length - 1], '#18cfbb'); // 终点

      // 绘制动画点（带闪烁效果）
      const animatedPoint = this.getAnimatedPoint(this.animationProgress);
      this.drawFlashPoint(ctx, animatedPoint);

      ctx.draw();
    },

    // 绘制点
    drawPoint(ctx, point, color) {
      ctx.beginPath();
      ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
      ctx.fillStyle = color;
      ctx.fill();
    },

    // 绘制闪烁点
    drawFlashPoint(ctx, point) {
      const flashSize = 10 + Math.sin(this.flashProgress) * 3; // 大小变化
      const flashColor = `hsl(${Math.sin(this.flashProgress) * 60 + 120}, 100%, 50%)`; // 颜色变化

      ctx.beginPath();
      ctx.arc(point.x, point.y, flashSize, 0, Math.PI * 2);
      ctx.fillStyle = "#18cfbb";
      ctx.fill();
    },

    // 获取动画点坐标
    getAnimatedPoint(progress) {
      const totalSegments = this.points.length - 1; // 总段数
      const segmentProgress = progress * totalSegments; // 当前段进度
      const segmentIndex = Math.floor(segmentProgress); // 当前段索引
      const t = segmentProgress - segmentIndex; // 当前段内的进度

      const startPoint = this.points[segmentIndex];
      const endPoint = this.points[segmentIndex + 1];

      if (segmentIndex % 3 === 2) {
        // 贝塞尔曲线部分
        const controlPoint = this.points[segmentIndex];
        const x =
          Math.pow(1 - t, 2) * startPoint.x +
          2 * (1 - t) * t * controlPoint.x +
          Math.pow(t, 2) * endPoint.x;
        const y =
          Math.pow(1 - t, 2) * startPoint.y +
          2 * (1 - t) * t * controlPoint.y +
          Math.pow(t, 2) * endPoint.y;
        return { x, y };
      } else {
        // 折线部分
        const x = startPoint.x + (endPoint.x - startPoint.x) * t;
        const y = startPoint.y + (endPoint.y - startPoint.y) * t;
        return { x, y };
      }
    },

    // 开始动画
    startAnimation() {
      const duration = 19000; // 动画时长（毫秒）
      const startTime = Date.now();

      const animate = () => {
		  this.num++;
        const currentTime = Date.now();
        const elapsed = currentTime - startTime;
        this.animationProgress = Math.min(elapsed / duration, 1);
        this.flashProgress = (elapsed / 200) % (Math.PI * 2); // 闪烁效果进度

        this.drawSmoothTrack();

        if (this.animationProgress < 1) {
			if(this.num%60===0){
				let tempnum  = this.kmnum;
				tempnum += 0.1;
				if(String(tempnum).length>5){
					this.kmnum = Number(tempnum.toFixed(2))
				}else{
					this.kmnum = tempnum;
				}
			}
			if(!this.isover){
				// requestAnimationFrame(animate);
				setTimeout(animate,10)
			}
        } else {
          // 动画结束后重置
          this.animationProgress = 0;
          this.startAnimation();
        }
      };

      animate();
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: center;
  /* align-items: center; */
  height: 100vh;
  background-color: #f0f0f0;
  background-image: url(/static/imgs/3.png);
  background-size: 100% 75%;
  background-repeat: no-repeat;
}

.canvas {
  /* background-color: #fff; */
  /* border: 1px solid #ccc; */
}
.showkm{
	width: 100%;
	height: 100upx;
	line-height: 100upx;
	/* border: 1px solid; */
	position: absolute;
	bottom: 200upx;
	text-align: center;
	font-size: 80upx;
	color: #296049;
}
.stopclass{
	width: 150upx;
	height: 150upx;
	border-radius:50%;
	// border: 1px solid;
	position: absolute;
	bottom: 20upx;
	display: flex;
	justify-content: center;
	align-items: center;
}
@import "../../../style/color/color.scss"; //颜色
/* 运动颜色 数据库取出 */
	.yd-red{
		background: $redColor-linear;
	}
	.yd-blue{
		background: $blueColor-linear;
	}
	.yd-purple{
		background: $purpleColor-linear;
	}
	.yd-black{
		background: $blackColor-linear;
	}
	.yd-cyan{
		background: $cyanColor-linear;
	}
</style>